﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using HtmlAgilityPack;
using System.Windows.Forms;

namespace Searching
{
    public partial class Form1 : Form
    {
        private readonly HttpClient _httpClient;
        public Form1()
        {
            InitializeComponent();  //Http配置
            _httpClient = new HttpClient(new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            });
            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
            _httpClient.Timeout = TimeSpan.FromSeconds(15);
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            txtBaidu.Clear();
            txtBing.Clear();
            btnSearch.Enabled = false;

            var keyword = txtKeyword.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键字");
                btnSearch.Enabled = true;
                return;
            }

            try
            {
                var tasks = new Task[] {
                    SearchBaiduAsync(keyword),
                    SearchBingAsync(keyword)
                };
                await Task.WhenAll(tasks);
            }
            finally
            {
                btnSearch.Enabled = true;
            }
        }

        private async Task SearchBaiduAsync(string keyword)
        {
            var url = $"https://www.baidu.com/s?wd={WebUtility.UrlEncode(keyword)}";

            var html = await GetHtmlWithRetry(url);
            if (html == null)
            {
                UpdateTextBox(txtBaidu, "获取百度结果失败");
                return;
            }

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            // 最新的XPath选择器（测试于2024-04）
            var nodes = doc.DocumentNode.SelectNodes(
                "//div[contains(@class, 'content-right_')]//span[contains(@class, 'content_')]");

            if (nodes == null || nodes.Count == 0)
            {
                UpdateTextBox(txtBaidu, "未找到有效结果");
                return;
            }

            var result = new StringBuilder();
            foreach (var node in nodes)
            {
                var text = WebUtility.HtmlDecode(node.InnerText?.Trim());
                if (!string.IsNullOrWhiteSpace(text))
                {
                    result.Append(text);
                    if (result.Length >= 200) break;
                    result.Append(" "); 
                }
            }

            UpdateTextBox(txtBaidu, result.Length > 0
                ? GetSafeSubstring(result.ToString(), 200)
                : "无可用文本");
        }

        private async Task SearchBingAsync(string keyword)
        {
            var url = $"https://www.bing.com/search?q={WebUtility.UrlEncode(keyword)}";

            var html = await GetHtmlWithRetry(url);
            if (html == null)
            {
                UpdateTextBox(txtBing, "获取必应结果失败");
                return;
            }

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var nodes = doc.DocumentNode.SelectNodes(
                "//div[@class='b_caption']/p");

            if (nodes == null || nodes.Count == 0)
            {
                UpdateTextBox(txtBing, "未找到有效结果");
                return;
            }

            var result = new StringBuilder();
            foreach (var node in nodes)
            {
                var text = WebUtility.HtmlDecode(node.InnerText?.Trim());
                if (!string.IsNullOrWhiteSpace(text))
                {
                    result.Append(text);
                    if (result.Length >= 200) break;
                    result.Append(" ");
                }
            }

            UpdateTextBox(txtBing, result.Length > 0
                ? GetSafeSubstring(result.ToString(), 200)
                : "无可用文本");
        }

        private async Task<string> GetHtmlWithRetry(string url, int retries = 2)
        {
            for (int i = 0; i < retries; i++)
            {
                try
                {
                    var response = await _httpClient.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
                catch
                {
                    if (i == retries - 1) throw;
                    await Task.Delay(1000);
                }
            }
            return null;
        }

        private string GetSafeSubstring(string text, int maxLength)
        {
            if (string.IsNullOrEmpty(text)) return string.Empty;
            return text.Length <= maxLength ? text : text.Substring(0, maxLength);
        }

        private void UpdateTextBox(RichTextBox textBox, string content)
        {
            if (textBox.InvokeRequired)
            {
                textBox.BeginInvoke(new Action(() => textBox.Text = content));
            }
            else
            {
                textBox.Text = content;
            }
        }
    }
}
